package com.example.demo.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.example.demo.controller.vo.ResponseResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.mybatis.spring.MyBatisSystemException;
import java.sql.SQLException;

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ResponseResult<?>> handleBusinessException(BusinessException ex) {
        logger.warn("Business exception: {}", ex.getMessage());
        return new ResponseEntity<>(
            ResponseResult.error(ex.getErrorCode().getCode(), ex.getMessage()),
            HttpStatus.BAD_REQUEST
        );
    }

    @ExceptionHandler(MyBatisSystemException.class)
    public ResponseEntity<ResponseResult<?>> handleMyBatisException(MyBatisSystemException ex) {
        logger.error("Database operation failed: ", ex);
        String message = "Database operation failed";
        if (ex.getCause() != null) {
            message = ex.getCause().getMessage();
        }
        return new ResponseEntity<>(
            ResponseResult.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), message),
            HttpStatus.INTERNAL_SERVER_ERROR
        );
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResponseResult<?>> handleException(Exception ex) {
        logger.error("An error occurred: ", ex);
        String message = ex.getMessage();
        if (ex instanceof SQLException) {
            message = "Database error: " + message;
        }
        return new ResponseEntity<>(
            ResponseResult.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), message),
            HttpStatus.INTERNAL_SERVER_ERROR
        );
    }
}
